package com.erebus.centroller;


import com.erebus.feignclient.AuthServiceClient;
import com.erebus.model.dto.GoodsDto;
import com.erebus.model.dto.OrderDto;
import com.erebus.model.dto.OrderDtos;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.base.model.RestResponse;
import com.taobao.base.model.TokenResponse;
import com.taobao.base.model.TokenUser;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
public class SeckillController {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AuthServiceClient authServiceClient;


    @GetMapping("/getGoods")
    public RestResponse<List<GoodsDto>> getGoods(){
        long startTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
//        long startTime = LocalDateTime.now().plusMinutes(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long endTime = LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        GoodsDto goodsDto = new GoodsDto(91, "戴森吹风机", 2999.99f, "http://103.36.222.137:9000/taobao/img/4.png", startTime, endTime);
        ArrayList<GoodsDto> list = new ArrayList<>();
        list.add(goodsDto);

        return RestResponse.success(list);
    }

    // 抢购下单接口
    @PostMapping("/SendDirect")
    public RestResponse<String> SendDirect(@RequestBody OrderDto orderDto, HttpServletRequest request) throws JsonProcessingException {
        String exchangeName = "taobao.direct";
        String routingKey = "order";
        TokenUser tokenUser = null;

        // 从请求头中获取 Authorization 字段
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
        } else {
            System.err.println("No valid token found in the Authorization header.");
        }
        if (tokenUser == null) {
            return RestResponse.validfail("用户未登录");
        }
        OrderDtos orderDtos = new OrderDtos();
        orderDtos.setUserId(tokenUser.getUserId());
        BeanUtils.copyProperties(orderDto, orderDtos);
        // 将 OrderDto 转换为 Map
        Map<String, Object> msg = objectMapper.convertValue(orderDtos, Map.class);
        // 创建 CorrelationData 并设置唯一 ID
        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
        try {
            rabbitTemplate.convertAndSend(exchangeName, routingKey, msg, cd);
            System.out.println("消息已发送，内容：" + msg);
        } catch (Exception e) {
            System.err.println("消息发送失败，原因：" + e.getMessage());
        }
        return RestResponse.success("订单已发送");
    }
    /**
     * 解析token 获取用户信息
     */
    private TokenUser getTokenUser(HttpServletRequest request) {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenUser;
    }
}
